const mysql = require('mysql2/promise');
const config = require('../config/config');

// 创建连接池
const pool = mysql.createPool({
    host: config.db.host,
    user: config.db.user,
    password: config.db.password,
    database: config.db.database,
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
});

// 测试数据库连接
async function testConnection() {
    try {
        const connection = await pool.getConnection();
        console.log('数据库连接成功！');
        connection.release();
    } catch (error) {
        console.error('数据库连接失败：', error);
    }
}

// 执行SQL查询的通用方法
async function query(sql, params) {
    try {
        const [rows] = await pool.execute(sql, params);
        return rows;
    } catch (error) {
        console.error('SQL查询错误：', error);
        throw error;
    }
}

module.exports = {
    pool,
    query,
    testConnection
};